<template>
  <div class="conversations">

    <!--  往期会话选择列表  -->
    <div class="conversation-list">
      <div class="conversation-list-container">
        <div class="conversation-list-content">
          <div v-if="conversations.length">
            <div
              v-for="(conversation, key) in conversations" :key="key"
              @click="changeFriend(conversation)"
            >
              <div class="conversation" :class="{actived:decideActiveClass(conversation)}" @contextmenu.prevent.stop="e => showRightClickMenu(e,conversation)">
                <div class="avatar">
                  <img :src="currentUser.id === conversation.userIdPash?conversation.pullHeader:conversation.pashHeader"/>
                  <div v-if="conversation.unread>0"
                       class="unread-count">
                    <span class="unread">{{ conversation.unread }}</span>
                  </div>
                </div>
                <div class="conversation-message">
                  <div class="conversation-top">
                    <span class="conversation-name">{{ currentUser.id === conversation.userIdPash? conversation.pullName:conversation.pashName}}</span>
                    <div class="conversation-time">
                      <div>{{ formatDate(conversation.createTime) }}</div>
                    </div>
                  </div>
                  <div class="conversation-bottom">
                    <div class="conversation-content" v-if="conversation.recalled===0">
<!--                      <div v-if="conversation.type === 'private'">-->
<!--                        {{-->
<!--                          conversation.lastMessage.senderId === currentUser.id ? '你' : `"${conversation.data.name}"`-->
<!--                        }}撤回了一条消息-->
<!--                      </div>-->
<!--                      <div v-if="conversation.type === 'group'">-->
<!--                        {{-->
<!--                          conversation.lastMessage.senderId === currentUser.id ? '你' : `"${conversation.lastMessage.senderData.name}"`-->
<!--                        }}撤回了一条消息-->
<!--                      </div>-->
                    </div>

                    <div class="conversation-content" v-else>
                      <div class="unread-text"
                           v-if="conversation.readStatus ==0 && conversation.userIdPull === currentUser.id">
                        [未读]
                      </div>
                      <div >
                        {{ conversation.userIdPash === currentUser.id ? '我' : conversation.pashName }}:
                      </div>
                      <span class="text"
                            v-if="conversation.messgeText !== null">{{
                          conversation.messgeText
                        }}</span>
<!--                      <span v-if="conversation.lastMessage.type === 'video'">[视频消息]</span>-->
<!--                      <span v-if="conversation.lastMessage.type === 'audio'">[语音消息]</span>-->
                      <span v-if="conversation.messgeLink !== null">[链接]</span>
                      <span v-if="conversation.messgeImage !==null">[图片消息]</span>
<!--                      <span v-if="conversation.lastMessage.type === 'file'">[文件消息]</span>-->
<!--                      <span v-else-if="conversation.lastMessage.type === 'order'">[订单消息]</span>-->
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="no-conversation">- 当前没有会话 -</div>
        </div>
      </div>
      <div v-if="rightClickMenu.visible" :style="{'left': rightClickMenu.x + 'px', 'top': rightClickMenu.y + 'px'}"
           class="action-box">
        <div class="action-item" @click="topConversation">{{ rightClickMenu.conversation.top ? '取消置顶' : '置顶' }}</div>
        <div class="action-item" @click="deleteConversation">删除聊天</div>
      </div>
    </div>

    <!--  会话框  -->
    <div class="chat">

      <Component :is="componentName" :friendId="friendId"  :currentUser="currentUser" :stompClient="stompClient" :messagePrivate="messagePrivate"></Component>
    </div>

  </div>
</template>

<script>
import privateChat from "@/views/chat/session/PrivateChat";
import groupChat from "@/views/chat/session/GroupChat";
import {getAllchatLastOne} from "@/api/chat/user";
import {addMessage, updateMessage} from "@/api/chat/message";

export default {
    name: 'Conversations',
    components: {
      privateChat, groupChat
    },
    props: [
      'chatFriend','currentUser','stompClient','messagePrivateCheck'
    ],
    data() {
      return {
        componentName:"",
        // currentUser: {//当前用户信息
        //   "id": "3bb179af-bcc5-4fe0-9dac-c05688484649",
        //   "name": "Wallace",
        //   "password": "123",
        //   "avatar": "http://192.168.8.247:9300/statics/2023/07/24/5_20230724130842A017.jpg",
        //   "email": "Wallace@goeasy.io",
        //   "phone": "138xxxxxxxx"
        // },
        conversations: [],//存每个好友聊天记录会话列表的最后一个记录
        friendId:0,
        messagePrivate:null,//通过收取到的 messagePrivateCheck 检查，改变部分值再传给私聊页
        // Conversation右键菜单
        rightClickMenu: {
          conversation: null,
          visible: false,
          x: null,
          y: null,
        },
      };
    },
    created() {

      this.friendId=0
      this.getConversations()//得到最近聊天列表并打开列表

    },
    watch:{
      messagePrivateCheck:{//如果消息接收到，判断当前是不是在和好友对话，如果是，就将消息传递过去，并将消息改为已读，存数据库
        //如果不是，(先判断消息列表里有没有，如果有，先删掉，然后再在列表中添加一个聊天列再第一位，并增加一个未读消息
        handler(newMessage,oldMessage){
          if (newMessage.userIdPash==this.friendId){
            this.messagePrivateCheck.readStatus = 1
            this.messagePrivate = this.messagePrivateCheck
            this.submitFormMessagePrivate()//将存数据库的消息修改一些
          }else {//重新执行列表查询
            this.getConversations()
          }
        }
      }
    },
    beforeDestroy() {

    },
    methods: {
      formatDate(t) {
        t = t || Date.now();
        let time = new Date(t);
        let str = time.getMonth() < 9 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1;
        str += '-';
        str += time.getDate() < 10 ? '0' + time.getDate() : time.getDate();
        str += ' ';
        str += time.getHours();
        str += ':';
        str += time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes();
        return str;
      },

      listenConversationUpdate() {
        // 监听会话列表变化

      },
      renderConversations(content) {
        this.conversations = content.conversations;
      },
      subscribeGroup() {

      },
      showRightClickMenu(e, conversation) {
        this.rightClickMenu.conversation = conversation;
        this.rightClickMenu.visible = true;
        this.rightClickMenu.x = e.pageX;
        this.rightClickMenu.y = e.pageY;
      },
      hideRightClickMenu() {
        this.rightClickMenu.visible = false;
      },
      topConversation() {
        let conversation = this.rightClickMenu.conversation;
        let description = conversation.top ? '取消置顶' : '置顶';

      },
      deleteConversation() {
        if (confirm('确认要删除这条会话吗？')) {
          let conversation = this.rightClickMenu.conversation;

        }
      },
      chatLocation(conversation) {
        let path = conversation.type === 'private' ?
          '/conversations/privatechat/' + conversation.userId :
          '/conversations/groupchat/' + conversation.groupId
        return {
          path: path,
          query: {
            name: conversation.data.name,
            avatar: conversation.data.avatar
          }
        }
      },
      getConversations(){//得到最近聊天列表
        //先进行查询聊天记录，取前十个不同的好友id的最近时间的一条记录
        getAllchatLastOne(this.currentUser.id,10).then(allchatLastOne=>{
          this.conversations = allchatLastOne.data
          if (this.chatFriend=='undefined'||this.chatFriend==0){
            return;
          }
          if (this.conversations.length>0){
            //这里做个判断，如果历史好友id和想聊的id相等，那么应该直接选中，而不是新增一个
            let result = this.judgeIdEqual()
            if (result!==undefined){
              this.changeFriend(result)//执行打开聊天窗口
              return;//直接结束流程，不执行下面的内容
            }
          }
          let chatFriend = {
            id:null,
            messgeImage:null,
            messgeLink:null,
            messgeText:null,
            pashHeader:this.currentUser.headImage,
            pashName:this.currentUser.nickName,
            pullHeader:this.chatFriend.headImage,
            pullName:this.chatFriend.nickName,
            readStatus:null,
            recalled:1,
            remark:null,
            updateTime:'',
            createTime:'',
            userIdPash:this.currentUser.id,
            userIdPull:this.chatFriend.id
          }
          this.conversations.unshift(chatFriend)
          this.componentName="privateChat" //打开私聊页面
          this.friendId = this.chatFriend.id//改变值
        });
      },
      judgeIdEqual(){
        return this.conversations.find(item => {
          return item.userIdPash == this.chatFriend.id || item.userIdPull == this.chatFriend.id
        })
      },
      changeFriend(conversation){
        // while (conversation !== null)
        //重新刷新一下最近聊天好友列表

        this.componentName="privateChat" //打开私聊页面
        this.getConversations()
        if (conversation !== null&&conversation !== 0){
          this.currentUser.id === conversation.userIdPash?this.friendId=conversation.userIdPull:this.friendId=conversation.userIdPash
        }else {
          this.friendId=this.chatFriend.id
          // this.decideActiveClass()//改变选中好友
        }

        //判断conversation是否不为空，然后再判断有没有和该好友的聊天列，没有就创建一个，有就将该聊天项改为选中状态
        //如果conversation为空，则需要在conversations集合添加一个聊天记录
      },
      decideActiveClass(conversation){
        // if (conversation !== null&&conversation !== 0){
        //   return false
        // }
        //判断是否要显示选中效果
        if (conversation !== null){
          if(this.currentUser.id === conversation.userIdPash){
           return conversation.userIdPull===this.friendId
          }else {
            return conversation.userIdPash===this.friendId
          }
        }else{
          return true
        }
      },
      submitFormMessagePrivate(){//将存数据库的消息修改一些
        updateMessage(this.messagePrivate).then(response => {
        });
      }
    },
  };
</script>

<style scoped>
  .conversations {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    color: #333333;
  }

  .conversation-list {
    width: 220px;
  }

  .conversation-list-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: white;
    border-right: #dbd6d6 1px solid;
  }

  .conversation-list-content {
    flex: 1;
    overflow-y: auto;
    padding: 10px 0;
    scrollbar-width: none;
    -ms-overflow-style: none;
  }

  .conversation-list-content::-webkit-scrollbar {
    display: none;
  }

  .no-conversation {
    text-align: center;
    color: #666666;
  }

  .conversation {
    display: flex;
    padding: 10px 5px;
    cursor: pointer;
  }

  .unread-count {
    position: absolute;
    top: -10px;
    left: 30px;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    color: white;
    background: #d02129;
  }

  .unread-count .unread {
    display: block;
    font-size: 12px;
    text-align: center;
    line-height: 18px;
  }

  .conversation-message {
    flex: 1;
    padding-left: 5px;
    display: flex;
    width: 160px;
    flex-direction: column;
    justify-content: space-around;
  }

  .conversation-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    text-align: right;
  }

  .conversation-name {
    font-size: 12px;
    font-weight: 500;
  }

  .conversation-time {
    width: 75px;
    color: #B9B9B9;
    display: flex;
    flex-direction: column;
  }

  .conversation-bottom {
    display: flex;
    color: #666666;
  }

  .conversation-content {
    display: flex;
    width: 160px;
    color: #b3b3b3;
  }

  .conversation-content .text {
    overflow: hidden;
    text-overflow: ellipsis;
    flex: 1;
    white-space: nowrap;
    word-break: break-all;
  }

  .conversation-bottom .unread-text {
    color: #d02129;
    width: 35px !important;
  }

  .conversation .avatar {
    width: 40px;
    height: 40px;
    position: relative;
  }

  .conversation .avatar img {
    width: 100%;
    height: 100%;
    border-radius: 10%;
  }

  .router-link-active {
    background: #eeeeee;
  }

  .action-box {
    width: 100px;
    height: 60px;
    background: #ffffff;
    border: 1px solid #cccccc;
    position: fixed;
    z-index: 100;
    border-radius: 5px;
  }

  .action-box .action-item {
    padding-left: 15px;
    line-height: 30px;
    font-size: 13px;
    color: #262628;
    cursor: pointer;
  }

  .action-box .action-item:hover {
    background: #dddddd;
  }

  .chat {
    flex: 1;
    display: flex;
  }

  .actived {
    border-radius: 10px;
    box-shadow: inset 0 0px 4px 0px rgb(112 169 166);
  }

</style>
